import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {Alert, message, Tabs} from 'antd';
import React, {useState} from 'react';
import {ProFormText, LoginForm} from '@ant-design/pro-form';
import {FormattedMessage, SelectLang, history, useModel} from 'umi';
import Footer from '@/components/Footer';

import styles from './index.less';
import {systemLogin} from "@/pages/System/Login/service";
import {putAccessToken, setGuidList} from "@/utils/localStoreUtil";

const LoginMessage: React.FC<{
  content: string;
}> = ({content}) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<any>({});
  const {initialState, setInitialState} = useModel('@@initialState');

  const initInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    const menuList = await initialState?.getMenuList?.();

    if (userInfo && menuList) {
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
        menuData:menuList
      }));
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const res = await systemLogin({...values});
      if (res.code === 10000) {
        const token = res.data.token;
        // 添加token 到缓存中
        putAccessToken(token);
        setGuidList(res.data.authIds);
        // 初始化信息
        await initInfo();
        message.success("登录成功");
        let pushUrl = '/welcome'

        if (initialState?.menuData && initialState.menuData.length > 0) {
          pushUrl = initialState.menuData[0]?.path || '/welcome';
        }

        history.push(pushUrl);
        return;
      }
      // 如果失败去设置用户错误信息
      setUserLoginState(res);
    } catch (error) {
      message.error("登录失败，请重试！");
    }
  };
  const {code} = userLoginState;

  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang/>}
      </div>
      <div className={styles.content}>
        <LoginForm
          logo={<img alt="logo" src="/logo.svg"/>}
          title="系统配置后台"
          subTitle={'管理您的后台菜单、系统配置等'}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs>
            <Tabs.TabPane
              key="account"
              tab="账户密码登录"
            />
          </Tabs>

          {code === 10006 && (
            <LoginMessage
              content="账户或密码错误"
            />
          )}
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon}/>,
              }}
              placeholder="请输入用户名"
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.username.required"
                      defaultMessage="请输入用户名!"
                    />
                  ),
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon}/>,
              }}
              placeholder="请输入密码"
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.required"
                      defaultMessage="请输入密码！"
                    />
                  ),
                },
              ]}
            />
          </>
        </LoginForm>
      </div>
      <Footer/>
    </div>
  );
};

export default Login;
